package com.lbj.mall.order.interceptor;

import com.lbj.mall.common.constant.APPConstant;
import com.lbj.mall.common.entity.vo.MemberVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 用户登录拦截器
 */
@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberVo> userLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        MemberVo memberVo = (MemberVo) request.getSession().getAttribute(APPConstant.SAVE_LOGIN_USER);

        if (memberVo == null) {
            // 用戶未登錄，重定向到登录页面
            log.info("用户未登录...");
            request.getSession().setAttribute("msg", "请先登录");
            response.sendRedirect("http://auth.localmall.com/login.html");
            return false; // 未登录不放行
        } else {
            // 如果已登录将用户信息保存到ThreadLocal中，保证后续请求都可以拿到用户信息
            userLocal.set(memberVo);
            return true;
        }
    }
}
